package org.example.testdemo.exception;

import org.example.testdemo.tool.ApiResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ApiResponse handleException(Exception e) {
        if(e.toString().contains("jakarta.validation.ConstraintViolationException:")){
            String[] errorIndex = e.getMessage().split(",");
            StringBuilder errorMsg = new StringBuilder();
            for (String error : errorIndex) {
                int delimiterIndex = error.indexOf(":");
                errorMsg.append(error.substring(delimiterIndex + 1)).append(",");
            }
            return ApiResponse.fail(-1,errorMsg.toString());
        }
        System.out.println(e.toString());
        return ApiResponse.error();
    }

}
